<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="viewport" content="width=device-width, initial-scale=1.0">
    <meta charset="UTF-8">
    <title>需求发布平台</title>
    <link rel="stylesheet" href="publisher/css/base/reset.css">
    <link rel="stylesheet" href="publisher/css/components/navbar.css">
    <link rel="stylesheet" href="publisher/css/components/editor.css">
    <link rel="stylesheet" href="publisher/css/components/maintenance.css">
    <link rel="stylesheet" href="publisher/css/components/messages.css">
    <link rel="stylesheet" href="publisher/css/main.css">
    <!-- 添加Markmap相关库 -->
    <script src="https://cdn.jsdelivr.net/npm/d3@7"></script>
    <script src="https://cdn.jsdelivr.net/npm/markmap-lib@0.15.3/dist/browser/index.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/markmap-view@0.15.3/dist/browser/index.js"></script>
    <style>
        .mindmap-container {
            height: calc(100% - 40px);
            border: 1px solid #ddd;
            border-radius: 4px;
            background-color: #fafafa;
        }

        .mindmap-placeholder {
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #999;
            font-size: 14px;
        }
    </style>
</head>
<body>
<nav class="navbar">
    <div class="nav-left">
        <div class="nav-item active">新建需求</div>
        <div class="nav-item">需求维护池</div>
        <div class="nav-item">消息</div>
    </div>
    <div class="user-info">
        <span>张三</span>
        <div class="avatar"></div>
        <div class="user-dropdown">
            <div>手机号/邮箱：
                <span id="user-contact">已登录的手机号或邮箱</span>
            </div>
            <div class="upload-avatar">
                <img src="publisher/assets/images/avatar-placeholder.png" alt="头像">
                <a href="#" id="upload-avatar-link">上传/修改头像</a>
            </div>
            <button id="change-password-btn">修改密码</button>
        </div>
    </div>
</nav>

<div class="container">
    <div class="top-section">
        <div class="mind-map">
            <h3 style="margin-bottom: 12px; color: #333;">需求脑图</h3>
            <!-- 思维导图容器 -->
            <div id="mindmap-container" class="mindmap-container">
                <div class="mindmap-placeholder">
                    请在右侧输入需求内容，将自动生成思维导图
                </div>
            </div>
        </div>

        <div class="description">
            <h3 style="margin-bottom: 12px; color: #333;">需求描述</h3>
            <textarea id="demand-description" placeholder="请输入详细的需求描述..."></textarea>
        </div>
    </div>
    <div class="bottom-section">
        <textarea class="input-demand" id="input-demand" placeholder="输入您的需求内容...（支持Markdown格式）"></textarea>
        <button class="confirmsub-btn" id="confirmsub-btn">⬆️ 确定需求</button>
        <button class="upload-btn">
            <span>📎 上传附件</span>
            <input type="file" hidden multiple>
        </button>
    </div>
    <div class="middle-area">
        <button class="create-btn">创建新需求</button>
    </div>
</div>

<div class="maintenance-container">
    <div class="left-nav">
        <div class="dropdown main-demand-dropdown">
            选择已发布的需求
            <div class="dropdown-content">
                <div data-demand-id="1">主需求一</div>
                <div data-demand-id="2">主需求二</div>
            </div>
        </div>
        <div class="dropdown sub-demand-dropdown">
            下拉选择子需求
            <div class="dropdown-content">
                <div>子需求一</div>
                <div>子需求二</div>
            </div>
        </div>
        <div class="option" id="overview-option">概览</div>
        <div class="option" id="sub-demand-option">子需求</div>
    </div>
    <div class="right-content">
        <div class="overview">
            <h3 style="margin-bottom: 12px; color: #333;">子需求名称/某需求的概览：</h3>
        </div>

        <div class="horizontal-layout">
            <div class="mind-map">
                <h3 style="margin-bottom: 12px; color: #333;">需求脑图</h3>
                <div style="height: calc(100% - 40px); border: 1px dashed #ddd;
                         border-radius: 4px; display: grid; place-items: center;
                         color: #999;">
                    脑图区域（可集成专业脑图库）
                </div>
            </div>

            <div class="description">
                <h3 style="margin-bottom: 12px; color: #333;">需求描述</h3>
                <textarea placeholder="请输入详细的需求描述..."></textarea>
            </div>
        </div>


        <div class="history-section">
            <h3 style="margin-bottom: 12px; color: #333;">历史修改：</h3>
            <div class="history-item">
                <div class="content">某人修改：</div>
                <div class="content">原内容：<br>...</div>
                <div class="content">修改为：<br>...</div>
            </div>
        </div>

        <button class="save-btn">保存</button>
    </div>
</div>

<!-- 消息容器 -->
<div class="messages-container" style="display: none;">
    <div class="left-nav">
        <div class="demand-item active">需求一（名称）</div>
        <div class="demand-item">需求二</div>
    </div>
    <div class="right-content">
        <div class="demand-details">
            <div class="demand-name">需求名称：需求一（名称）</div>
            <div class="user-name">用户名称：用户11111</div>
            <div class="reply">回复：这里是专家的回复内容...</div>
            <button class="reply-btn">点击回复</button>
            <div class="reply-box">
                <textarea class="reply-textarea" placeholder="请输入您的回复内容..."></textarea>
                <button class="confirm-btn">确认</button>
            </div>
        </div>
        <div class="message-list">
            <!-- 评论和回复区分展示 -->
            <div class="message-item comment">
                <div class="sender">用户11111</div>
                <div class="content">请问这个需求什么时候可以完成？我比较着急。</div>
                <div class="time">2023-05-20 10:30</div>
            </div>
            <div class="message-item reply-message">
                <div class="sender">我的回复：</div>
                <div class="content">您好，这个需求我们正在处理中，预计下周可以完成。</div>
                <div class="time">2023-05-20 11:15</div>
            </div>
            <div class="message-item comment">
                <div class="sender">用户11111</div>
                <div class="content">好的，谢谢，希望能按时完成。</div>
                <div class="time">2023-05-20 14:20</div>
            </div>
            <div class="message-item reply-message">
                <div class="sender">我的回复：</div>
                <div class="content">我们会尽快处理，请您放心。</div>
                <div class="time">2023-05-20 15:30</div>
            </div>
        </div>
    </div>
</div>

<!-- 修改密码界面 -->
<div class="change-password-container" style="display: none;">
    <div class="change-password-form">
        <div>
            <label for="user-contact-display">手机号/邮箱</label>
            <input type="text" id="user-contact-display" disabled value="已登录的手机号或邮箱">
        </div>
        <div class="verification-container">
            <input type="text" id="verification-code" placeholder="验证码">
            <button id="get-verification-code">获取</button>
        </div>
        <div>
            <input type="password" id="new-password" placeholder="新密码">
        </div>
        <div>
            <input type="password" id="confirm-password" placeholder="确认新密码">
        </div>
        <div>
            <button id="confirm-change-password">确认修改</button>
        </div>
        <div>
            <button id="return-to-user-info">返回</button>
        </div>
    </div>
</div>

<!-- 上传头像表单 -->
<form id="avatar-upload-form" style="display: none;">
    <input type="file" id="avatar-upload" accept="image/*">
</form>

<script src="publisher/js/app.js"></script>
<!-- 添加需求发送和思维导图生成功能的脚本 -->
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const inputDemand = document.getElementById('input-demand');
        const confirmSubBtn = document.getElementById('confirmsub-btn');
        const demandDescription = document.getElementById('demand-description');
        const mindmapContainer = document.getElementById('mindmap-container');

        let isWaitingForResponse = false;
        let conversationId = "";
        let markmapInstance = null; // Markmap实例
        let transformer = null; // Transformer实例

        // 等待库加载完成
        function waitForMarkmap() {
            return new Promise((resolve) => {
                const checkLibrary = () => {
                    if (window.markmap && window.markmap.Markmap && window.markmap.Transformer) {
                        resolve();
                    } else {
                        setTimeout(checkLibrary, 100);
                    }
                };
                checkLibrary();
            });
        }

        // 初始化Markmap
        async function initMarkmap() {
            try {
                // 等待库加载
                await waitForMarkmap();

                // 清空容器
                mindmapContainer.innerHTML = '';

                // 创建SVG元素
                const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
                svg.style.width = '100%';
                svg.style.height = '100%';
                mindmapContainer.appendChild(svg);

                // 初始化transformer
                if (!transformer) {
                    transformer = new window.markmap.Transformer();
                }

                // 创建Markmap实例
                markmapInstance = new window.markmap.Markmap(svg, {
                    autoFit: true,
                    duration: 300,
                    maxWidth: 300,
                    color: (node) => {
                        // 根据层级设置不同颜色
                        const colors = ['#4CAF50', '#2196F3', '#FF9800', '#9C27B0', '#F44336'];
                        return colors[node.depth % colors.length];
                    }
                });

                return markmapInstance;
            } catch (error) {
                console.error('初始化Markmap失败:', error);
                return null;
            }
        }

        // 生成思维导图
        async function generateMindmap(markdownContent) {
            try {
                if (!markdownContent || markdownContent.trim() === '') {
                    // 显示占位符
                    mindmapContainer.innerHTML = '<div class="mindmap-placeholder">请在右侧输入需求内容，将自动生成思维导图</div>';
                    return;
                }

                // 等待库加载
                await waitForMarkmap();

                // 如果内容不是markdown格式，尝试转换为简单的markdown结构
                let processedContent = markdownContent;
                if (!markdownContent.includes('#') && !markdownContent.includes('*') && !markdownContent.includes('-')) {
                    // 简单文本转换为markdown格式
                    const lines = markdownContent.split('\n').filter(line => line.trim());
                    if (lines.length > 0) {
                        processedContent = `# ${lines[0]}\n\n${lines.slice(1).map(line => `- ${line}`).join('\n')}`;
                    }
                }

                // 初始化transformer（如果还没有）
                if (!transformer) {
                    transformer = new window.markmap.Transformer();
                }

                // 使用markmap-lib解析markdown
                const { root } = transformer.transform(processedContent);

                // 初始化或更新markmap
                if (!markmapInstance || !mindmapContainer.querySelector('svg')) {
                    await initMarkmap();
                }

                if (markmapInstance && root) {
                    // 渲染思维导图
                    markmapInstance.setData(root);
                    markmapInstance.fit();
                }

            } catch (error) {
                console.error('生成思维导图失败:', error);
                mindmapContainer.innerHTML = '<div class="mindmap-placeholder">思维导图生成失败，请检查内容格式</div>';
            }
        }

        // 监听需求描述变化，自动生成思维导图
        let mindmapTimer = null;
        async function onDescriptionChange() {
            // 防抖处理，避免频繁更新
            if (mindmapTimer) {
                clearTimeout(mindmapTimer);
            }

            mindmapTimer = setTimeout(async () => {
                const content = demandDescription.value;
                await generateMindmap(content);
            }, 500); // 500ms延迟
        }

        // 绑定文本框变化事件
        demandDescription.addEventListener('input', onDescriptionChange);
        demandDescription.addEventListener('change', onDescriptionChange);

        // 显示加载指示器
        function showLoadingIndicator() {
            // 在需求描述区域显示加载中提示
            demandDescription.value = "正在生成需求描述，请稍候...";
            demandDescription.disabled = true;

            // 在思维导图区域显示加载提示
            mindmapContainer.innerHTML = '<div class="mindmap-placeholder">正在生成思维导图...</div>';
        }

        // 移除加载指示器
        function removeLoadingIndicator() {
            demandDescription.disabled = false;
        }

        // 发送需求到服务器 - 支持流式响应
        async function sendDemand(demand) {
            try {
                // 显示加载指示器
                showLoadingIndicator();

                // 准备请求数据
                const requestData = {
                    query: demand,
                    user: "publisher-user-" + Date.now(),
                    inputs: {},
                    response_mode: "streaming",
                    conversation_id: conversationId
                };

                // 发送请求
                const response = await fetch('/api/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(requestData)
                });

                if (!response.ok || !response.body) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let accumulatedAnswer = ""; // 累积的answer内容
                let buffer = ""; // 缓冲区用于处理不完整的数据行
                let firstDataReceived = false; // 标记是否已收到第一个数据

                while (true) {
                    const {done, value} = await reader.read();
                    if (done) break;

                    // 解码chunk并添加到缓冲区
                    buffer += decoder.decode(value, {stream: true});

                    // 按行分割数据
                    const lines = buffer.split('\n');

                    // 保留最后一行（可能不完整）作为缓冲区
                    buffer = lines.pop() || '';

                    // 处理每一行
                    for (const line of lines) {
                        const trimmedLine = line.trim();

                        // 跳过空行
                        if (!trimmedLine) continue;

                        // 处理以 "data: " 开头的行
                        if (trimmedLine.startsWith('data: ')) {
                            const jsonStr = trimmedLine.substring(6); // 移除 "data: " 前缀

                            try {
                                const data = JSON.parse(jsonStr);

                                // 提取answer内容
                                if (data.answer) {
                                    // 如果是第一次接收到数据，清空加载提示
                                    if (!firstDataReceived) {
                                        demandDescription.value = "";
                                        firstDataReceived = true;
                                    }

                                    accumulatedAnswer += data.answer;
                                    // 实时更新文本框内容
                                    demandDescription.value = accumulatedAnswer;

                                    // 实时更新思维导图
                                    await onDescriptionChange();
                                }

                                // 更新conversation_id
                                if (data.conversation_id) {
                                    conversationId = data.conversation_id;
                                }

                                // 可以根据需要处理其他事件类型
                                if (data.event) {
                                    console.log('Event:', data.event);
                                }

                            } catch (parseError) {
                                console.warn('解析JSON失败:', parseError, '原始数据:', jsonStr);
                            }
                        }
                    }
                }

                // 处理缓冲区中剩余的数据
                if (buffer.trim()) {
                    const trimmedLine = buffer.trim();
                    if (trimmedLine.startsWith('data: ')) {
                        const jsonStr = trimmedLine.substring(6);
                        try {
                            const data = JSON.parse(jsonStr);
                            if (data.answer) {
                                // 如果是第一次接收到数据，清空加载提示
                                if (!firstDataReceived) {
                                    demandDescription.value = "";
                                    firstDataReceived = true;
                                }

                                accumulatedAnswer += data.answer;
                                demandDescription.value = accumulatedAnswer;

                                // 最终更新思维导图
                                await onDescriptionChange();
                            }
                            if (data.conversation_id) {
                                conversationId = data.conversation_id;
                            }
                        } catch (parseError) {
                            console.warn('解析最后数据失败:', parseError);
                        }
                    }
                }

                console.log('流式响应完成，总内容长度:', accumulatedAnswer.length);

            } catch (error) {
                console.error('发送需求错误:', error);
                demandDescription.value = `发送需求失败: ${error.message}`;
                mindmapContainer.innerHTML = '<div class="mindmap-placeholder">生成失败，请重试</div>';
            } finally {
                isWaitingForResponse = false;
                inputDemand.disabled = false;
                confirmSubBtn.disabled = false;
                removeLoadingIndicator();
            }
        }

        // 绑定确认按钮点击事件
        confirmSubBtn.addEventListener('click', function() {
            const demand = inputDemand.value.trim();
            if (!demand) {
                alert('请输入需求内容');
                return;
            }

            if (isWaitingForResponse) {
                alert('正在处理中，请稍候...');
                return;
            }

            isWaitingForResponse = true;
            inputDemand.disabled = true;
            confirmSubBtn.disabled = true;

            // 发送需求
            sendDemand(demand);
        });

        // 支持回车键发送（Ctrl+Enter）
        inputDemand.addEventListener('keydown', function(e) {
            if (e.ctrlKey && e.key === 'Enter') {
                e.preventDefault();
                confirmSubBtn.click();
            }
        });

        // 初始化时显示占位符
        mindmapContainer.innerHTML = '<div class="mindmap-placeholder">请在右侧输入需求内容，将自动生成思维导图</div>';

        // 预加载Markmap库
        waitForMarkmap().then(() => {
            console.log('Markmap库加载完成');
        }).catch(error => {
            console.error('Markmap库加载失败:', error);
        });
    });
</script>
</body>
</html>